package com.powernode.filter;

import com.alibaba.fastjson.JSON;
import com.powernode.constant.AuthConstants;
import com.powernode.model.SecurityUser;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * token 解析过滤器类
 * OncePerRequestFilter : 每次请求过滤器
 */
@Component
public class TokenTranslationFilter extends OncePerRequestFilter {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * token解析过滤器
     * 获取请求头中的Authorization值 -->判断是否有值  --> 获取token值  -->  判断token是否有值
     * 处理token续约
     * 判断是否小于过期阈值
     * token转换为用户信息
     * 将json格式字符串的用户信息转换为SecurityUser对象
     * 处理权限
     * 创建security框架认识的用户对象
     * 将security框架认识的用户对象存放到security上下文中
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
        if (StringUtils.hasText(authorization)) {
            // 存在
            String token = authorization.replaceFirst(AuthConstants.BEARER, "");
            if (StringUtils.hasText(token)) {
                // token存在并拿到token
                // 拿到 有效时间
                Long expire = stringRedisTemplate.getExpire(AuthConstants.LOGIN_TOKEN_PREFIX + token, TimeUnit.SECONDS);
                if (expire < AuthConstants.TOKEN_EXPIRE_THRESHOLD_TIME) {
                    // 低于阈值 , 进行 token 续期
                    stringRedisTemplate.expire(AuthConstants.LOGIN_TOKEN_PREFIX + token, Duration.ofSeconds(AuthConstants.TOKEN_TIME));
                }

                // 获取 token key存储的 安全用户数据信息
                String userStr = stringRedisTemplate.opsForValue().get(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                // 将 json 数据 转为 securityUser对象 --> 将securityUser对象放到 公共基础服务中  , 并且需要添加JSON依赖
                SecurityUser securityUser = JSON.parseObject(userStr, SecurityUser.class);
                // 获取权限 并处理权限
                Set<SimpleGrantedAuthority> grantedAuthorities = securityUser.getPerms().stream()
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toSet());

                // 封装 用户对象为  security认识的数据格式
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser, null, grantedAuthorities);
                // 将数据放到 security上下文当中
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        // 向下传递
        filterChain.doFilter(request,response);
    }
}
